const fs = require('fs')
const componentDir = './src/components/lc/lc-components.vue'
const formatComponentName = (name) => {
    return name.split('').reduce((total, curr, idx, arr) => {
        if (curr === '-') {
            curr = '';
            arr[idx + 1] = arr[idx + 1].toUpperCase()
        }
        total += curr
        return total
    })
}
const templateAnnotation = '<!-- template end -->'
const importAnnotation = '// import end'
const componentsAnnotation = '// components end'

const presetTemplateSyntax = (type = 'basic', name = 'demo') => `<${formatComponentName(name)} :styles="item.style" :attribute="item.attribute" v-if="item.type === '${name}'" />`
const presetImportSyntax = (type = 'basic', name = 'demo') => `import ${formatComponentName(name)} from '../${type}/${name}/index.vue';`
const presetComponentsSyntax = (type = 'basic', name = 'demo') => formatComponentName(name) + ','

const SyntaxReplaceSet = [
    {
        annotation: templateAnnotation,
        handleFunc: (type, name) => presetTemplateSyntax(type, name)
    },
    {
        annotation: importAnnotation,
        handleFunc: (type, name) => presetImportSyntax(type, name)
    },
    {
        annotation: componentsAnnotation,
        handleFunc: (type, name) => presetComponentsSyntax(type, name)
    }
]


module.exports = {
    writeComponentsFile: (type, name) => {
        try {
            let content = fs.readFileSync(componentDir, 'utf-8')
            content = SyntaxReplaceSet.reduce((total, acc) => {
                const EndIndex = content.indexOf(acc.annotation)
                content = content.slice(0, EndIndex) + acc.handleFunc(type, name) + '\n' + content.slice(EndIndex, content.length)
                return content
            }, '')
            return fs.writeFileSync(componentDir, content, 'utf-8')
        } catch (error) {
            console.log(error);
        }

    }
}

// const templateAnnotationEndIndex = content.search(templateAnnotation)
// content = content.slice(0, templateAnnotationEndIndex) + presetTemplateSyntax() + '\n' + content.slice(templateAnnotationEndIndex, content.length)
// const presetImportAnnotationEndIndex = content.search(importAnnotation)
// content = content.slice(0, presetImportAnnotationEndIndex) + presetImportSyntax() + '\n' + content.slice(presetImportAnnotationEndIndex, content.length)
// const presetComponentsAnnotationEndIndex = content.search(componentsAnnotation)
// content = content.slice(0, presetComponentsAnnotationEndIndex) + presetComponentsSyntax() + '\n' + content.slice(presetComponentsAnnotationEndIndex, content.length)
